package com.example.egweibo1.controller;

import com.example.egweibo1.base.response.JsonResult;
import com.example.egweibo1.base.response.Status;
import com.example.egweibo1.mapper.UserMapper;
import com.example.egweibo1.pojo.dto.UserAddParam;
import com.example.egweibo1.pojo.dto.UserLoginParam;
import com.example.egweibo1.pojo.entity.User;
import com.example.egweibo1.pojo.vo.UserVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RestController
@Api(tags = "用户管理")
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    @ApiOperation("注册用户")
    @ApiOperationSupport(order = 10)
    public JsonResult addUser(@RequestBody @Validated UserAddParam userAddParam){
        User user = new User();
        log.debug("userAddParam="+userAddParam);
        BeanUtils.copyProperties(userAddParam,user);
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }
    @PostMapping("/login")
    @ApiOperation("登录用户")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam,@ApiIgnore HttpSession session){
        log.debug("userLoginParam="+userLoginParam);
        String username=userLoginParam.getUsername();
        String password=userLoginParam.getPassword();
        UserVo userVo=userMapper.selectUserByUsernameAndPassword(username,password);
        if(userVo==null){
            return new JsonResult(Status.FAIL,"用户名或密码错误");
        }
        session.setAttribute("user",userVo);
        return JsonResult.ok(userVo);
    }
    @GetMapping("/currentUser")
    @ApiOperation("获取当前登录用户信息")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVo userVo=(UserVo)session.getAttribute("user");
        if(userVo==null){
            return new JsonResult(Status.FAIL,"用户未登录");
        }
        return JsonResult.ok(userVo);
    }
    @GetMapping("/logout")
    @ApiOperation("用户登出")
    @ApiOperationSupport(order = 40)
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }




}
